package notice

import (
	"context"

	"mall/common/ctxdatax"
	"mall/common/enumx"
	"mall/service/forum/api/internal/logic/util"
	"mall/service/forum/api/internal/svc"
	"mall/service/forum/api/internal/types"
	"mall/service/forum/rpc/forumclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type NoticeListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewNoticeListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *NoticeListLogic {
	return &NoticeListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *NoticeListLogic) NoticeList(req *types.NoticeListReq) (resp *types.NoticeListResp, err error) {
	var page int64 = 1
	var pageSize int64
	if req.Current > 1 {
		page = req.Current
	}
	if req.PageSize > 0 { // 指定，检查最大值
		pageSize = req.PageSize
		if pageSize > l.svcCtx.Config.Query.MaxAmount {
			pageSize = l.svcCtx.Config.Query.MaxAmount
		}
	} else { // 不指定，使用默认值
		pageSize = l.svcCtx.Config.Query.DefaultAmount
	}

	userId := ctxdatax.GetUserId(l.ctx)
	var preload string
	var eagerLoad string
	preload = "forumNotice:Id,ForumId,ParentId,TopicId,PostId,Title,Desc,Extra,Type,Status,ReadAt,UpdatedAt"
	eagerLoad = "forumPost:total"
	res, err := l.svcCtx.ForumRpc.NoticeList(l.ctx, &forumclient.NoticeListReq{
		Offset:     int32((page-1)*pageSize),
		Limit:      int32(pageSize),
		Preload:    preload,
		EagerLoad:  eagerLoad,
		VisitorId:  int64(userId),
		PlatformId: int32(enumx.ThirdPartyPlatformWechatMini),
	})
	if err != nil {
		return nil, err
	}

	var list []*types.NoticeInfo
	if len(res.Data) > 0 {
		for _, item := range res.Data {
			list = append(list, &types.NoticeInfo{
				Id:             item.Id,
				UserId:         item.UserId,
				TopicId:        item.TopicId,
				PostId:         item.PostId,
				PerfumeId:      item.ParentId,
				NoticeType:     item.Type,
				NoticeTypeText: util.GetNoticeTypeText(item.Type),
				Title:          item.Title,
				Desc:           item.Desc,
				Extra:          item.Extra,
				Status:         item.Status,
				StatusText:     util.GetNoticeStatusText(item.Status),
				ReadAt:         item.ReadAt,
				CreatedAt:      util.GetTimeFromNow(item.UpdatedAt),
				UpdatedAt:      item.UpdatedAt,
				SourceType:     item.SourceType,
			})
		}
	}

	return &types.NoticeListResp{
		Current:         page,
		PageSize:        pageSize,
		List:            list,
		HasNextPage:     res.HasNextPage > 0,
		HasPreviousPage: res.HasPreviousPage > 0,
	}, nil
}
